package com.kobi.tapeRecorder;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;



public class MainActivity extends Activity {
	
	private Button mButton1;
	private Button mButton2;
	private SharedPreferences settings;
	
	public static final int RADIO_NONE = 0;
	public static final int RADIO_1 = 1;
	public static final int RADIO_5 = 5;
	public static final int RADIO_10 = 10;
	public static final String RECORD_LENGTH = "RecordLength";
	public static final String PARAMETERS = "Parameters";
	
	private String strRecordEnd2;
	
	public final static int RECORD_START = 0;
	public final static int RECORD_END = 1;
	
	public static final int MEDIA_MOUNTED = 0;
    public static final int MEDIA_MOUNTED_READ_ONLY = 1;
    public static final int NO_MEDIA = 2;
    private static final int TERMS = 3;
    
    private static final int NO_MEMORY_CARD = 2;
    
    private Context context;
	
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {

		public void handleMessage(Message message) {
			if (message.arg1 == RESULT_OK) {
				mButton1.setText(strRecordEnd2);
			} else {

			}

		};
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mButton1 = (Button) findViewById(R.id.button1);
        mButton2 = (Button) findViewById(R.id.button2);
        
        strRecordEnd2 = this.getString(R.string.main_string_record_start);
        
        final String strRecordStart = this.getString(R.string.main_string_record_start);
        final String strRecordEnd = this.getString(R.string.main_string_record_end);
        
        Intent i = getIntent();
		if (i.getBooleanExtra("RecordStatus", false))
			mButton1.setText(strRecordEnd);
		else
			mButton1.setText(strRecordStart);
        
        mButton1.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (String.valueOf(mButton1.getText()) == strRecordStart && updateExternalStorageState() == MEDIA_MOUNTED)
				{
					mButton1.setText(strRecordEnd);
					Intent myIntent = new Intent(MainActivity.this, RecordService.class);
					myIntent.putExtra("commandType", RECORD_START);
					Messenger messenger = new Messenger(handler);
					myIntent.putExtra("MESSENGER", messenger);
					myIntent.putExtra(RECORD_LENGTH, settings.getInt(RECORD_LENGTH, RADIO_NONE));
					startService(myIntent);
				}
				else if (String.valueOf(mButton1.getText()) == strRecordEnd && updateExternalStorageState() == MEDIA_MOUNTED)
				{
					mButton1.setText(strRecordStart);
					Intent myIntent = new Intent(MainActivity.this, RecordService.class);
					myIntent.putExtra("commandType", RECORD_END);
					startService(myIntent);	
					
				}
				else if (updateExternalStorageState() == MEDIA_MOUNTED_READ_ONLY || updateExternalStorageState() == NO_MEDIA)
				{
					showDialog(NO_MEMORY_CARD);
				}
			}
        	
        });
        
        
        mButton2.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (updateExternalStorageState() == MEDIA_MOUNTED)
				{
					Intent intent = new Intent(MainActivity.this, MainList.class);
		        	startActivity(intent);
				}
				else
					showDialog(NO_MEMORY_CARD);
				
			}
        	
        });
        
        context = this.getApplicationContext();
        settings = context.getSharedPreferences(PARAMETERS, 0);
        
        if (updateExternalStorageState() == MEDIA_MOUNTED_READ_ONLY || updateExternalStorageState() == NO_MEDIA) {
    		showDialog(NO_MEMORY_CARD);
        } 
        
        //showDialog(TERMS);
    }
    
    @Override
	protected Dialog onCreateDialog(int id) {
    	switch (id) {
		case NO_MEMORY_CARD:
			LayoutInflater li = LayoutInflater.from(this);
         
            AlertDialog.Builder categoryDetailBuilder = new AlertDialog.Builder(this);
            categoryDetailBuilder = new AlertDialog.Builder(this);
            categoryDetailBuilder.setMessage(R.string.dialog_no_memory);
            categoryDetailBuilder.setCancelable(false);
            categoryDetailBuilder.setPositiveButton(this.getString(R.string.dialog_close), new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                         dialog.cancel();
                   }
            });
            AlertDialog categoryDetail = categoryDetailBuilder.create();
            categoryDetail = categoryDetailBuilder.create();
         
           
          
          return categoryDetail;
		case TERMS:
			li = LayoutInflater.from(this);
	         
	          categoryDetailBuilder = new AlertDialog.Builder(this);
	          categoryDetailBuilder.setMessage(this.getString(R.string.dialog_privacy_terms));
	          categoryDetailBuilder.setCancelable(false);
	          categoryDetailBuilder.setPositiveButton(this.getString(R.string.dialog_terms), new DialogInterface.OnClickListener() {
	        	  public void onClick(DialogInterface dialog, int id) {
	        		  Intent i = new Intent(context, TermsActivity.class);
	          		  startActivity(i);
	        	  }
	          });
	          categoryDetailBuilder.setNegativeButton(this.getString(R.string.dialog_privacy), new DialogInterface.OnClickListener() {
	        	  public void onClick(DialogInterface dialog, int id) {
	        		  Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.privacychoice.org/policy/mobile?policy=306ef01761f300e3c30ccfc534babf6b"));
	              	  startActivity(browserIntent);
	        	  }
	          });
	          categoryDetailBuilder.setNeutralButton(this.getString(R.string.dialog_close), new DialogInterface.OnClickListener() {
	        	  public void onClick(DialogInterface dialog, int id) {
	        		  dialog.cancel();
	        	  }
	          });
	          categoryDetail = categoryDetailBuilder.create();
	         
	           
	          
	          return categoryDetail;
		default:
			break;
		}
		return null;
	}

	/**
	 * checks if an external memory card is available
	 * 
	 * @return
	 */
	public static int updateExternalStorageState() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return MEDIA_MOUNTED;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return MEDIA_MOUNTED_READ_ONLY;
		} else {
			return NO_MEDIA;
		}

	}
    
    /**
     * checks if my service is running
     * @return
     */
    private boolean isMyServiceRunning() { 
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); 
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 
            if ("com.kobi.tapeRecorder.RecordService".equals(service.service.getClassName())) { 
                return true; 
            } 
        } 
        return false; 
    }
    
    @Override
	public void onWindowFocusChanged(boolean hasFocus) {
    	if(hasFocus)
		{
    		String strRecordStart = this.getString(R.string.main_string_record_start);
	        String strRecordEnd = this.getString(R.string.main_string_record_end);
	        if (isMyServiceRunning())
    			mButton1.setText(strRecordEnd);
			else
	        	mButton1.setText(strRecordStart);
		}
		super.onWindowFocusChanged(hasFocus);
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_about:
				AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            	builder.setTitle(R.string.about_title)
            	.setMessage(R.string.about_content)
            	.setPositiveButton(R.string.about_close_button, new DialogInterface.OnClickListener() {
        			public void onClick(DialogInterface dialog, int id) {
        				dialog.cancel();
        			}
        		})
        		.show();
	        	break;
	        case R.id.menu_limt_time_rocord:
	        	Intent intent = new Intent(MainActivity.this, SettingActivity.class);
	        	intent.putExtra(RECORD_LENGTH, settings.getInt(RECORD_LENGTH, RADIO_NONE));
	        	startActivityForResult(intent, 1);
	        	break;
	        case R.id.menu_see_terms:
            	Intent i = new Intent(this.getBaseContext(), TermsActivity.class);
        		startActivity(i);
            	break;
            case R.id.menu_privacy_policy:
            	Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.privacychoice.org/policy/mobile?policy=306ef01761f300e3c30ccfc534babf6b"));
            	startActivity(browserIntent);
            	break;
	        default:
	        	break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if (requestCode == 1)
		{
			if (resultCode == RESULT_OK)
			{
				settings = this.getSharedPreferences(PARAMETERS, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.putInt(RECORD_LENGTH, data.getIntExtra(RECORD_LENGTH, RADIO_NONE));
				editor.commit();
			}
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
    
    
}
